<template>
  <x-back class="certification-page">
    <!-- 顶部按钮 -->
    <template #header v-if="isShowForm">
      <label>{{
        auditState === 1
          ? $t('certification.enterprise.certificationSuppier')
          : $t('certification.myEnterprise.enterpriseInfoModify')
      }}</label>
      <div class="title-btn">
        <el-button @click="handleSubmitCom"> {{ $t('common.save') }} </el-button>
        <el-button v-if="activeStep >= 1" type="primary" @click="handleSubmit('pre')">
          {{ $t('common.preStep') }}
        </el-button>
        <el-button type="primary" @click="handleSubmit(activeStep === 6 ? 'submit' : 'next')" :loading="loading">
          {{ activeStep === 6 ? $t('common.submit') : $t('common.nextStep') }}
        </el-button>
      </div>
    </template>
    <!-- 驳回弹窗 -->
    <el-alert v-if="auditState === 1" :title="'请完善资料后提交审核'" :type="'warning'"> </el-alert>
    <el-alert v-if="isEdit && auditState === 3" :title="'审核驳回'" :type="'error'" show-icon>
      <template>
        <div class="tips-contant">
          <div class="tips-text"> 驳回理由：{{ auditInfo.auditRemark }} </div>
          <span>驳回时间:{{ auditInfo.updateTime }}</span>
        </div>
      </template>
    </el-alert>
    <div class="main-panel" v-if="isShowForm">
      <certification-step ref="stepComponent" :active-step="activeStep" :step-options="stepList" />
      <div class="form-components">
        <div class="panl-title">
          <span>{{ stepList[activeStep].label || '' }}</span>
        </div>
        <transition name="fade-form">
          <!-- 基本信息-->
          <enterprise-form
            v-if="activeStep === 0"
            ref="baseComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />
          <!-- 法定代表人信息-->
          <representative-form
            v-if="activeStep === 1"
            ref="representComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />
          <!-- 企业负责人-->
          <responsible-person-form
            v-if="activeStep === 2"
            ref="responsibleComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />
          <!-- 股本结构-->
          <capital-structure-form
            v-if="activeStep === 3"
            ref="capitalComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />
          <!-- 发票信息-->
          <invoice-form
            v-if="activeStep === 4"
            ref="invoiceComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />

          <!-- 银行信息-->
          <bank-form
            v-if="activeStep === 5"
            ref="bankComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />

          <!-- 人员信息-->
          <person-form
            v-if="activeStep === 6"
            ref="personComponent"
            :dict-options="dictOptions"
            :supplier-id="supplierId"
          />
        </transition>
      </div>
    </div>
    <!-- 审核状态页面 -->
    <audit-state :audit-info="auditInfo" :dict-options="dictOptions" v-else @handleEdit="isEdit = true" />
  </x-back>
</template>
<script>
  import { QueryDictMixin, throttle } from '@package/utils'
  import { mapState, mapActions } from 'pinia'
  import CertificationStep from '../components/certificationStep.vue'
  import BankForm from '../components/bankForm.vue'
  import CapitalStructureForm from '../components/capitalStructureForm.vue'
  import EnterpriseForm from '../components/enterpriseForm.vue'
  import InvoiceForm from '../components/invoiceForm.vue'
  import RepresentativeForm from '../components/representativeForm.vue'
  import ResponsiblePersonForm from '../components/responsiblePersonForm.vue'
  import PersonForm from '../components/personForm.vue'
  import AuditState from '../components/auditState.vue'

  import { stepList } from '../config/certification'
  import { apiGetSubmit, apiPostAreaTree, apiPostGetServiceType } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  import { pinias } from '@/common/pinia'

  const { login } = pinias
  export default {
    name: 'Certification',
    components: {
      CertificationStep,
      BankForm,
      CapitalStructureForm,
      EnterpriseForm,
      InvoiceForm,
      RepresentativeForm,
      ResponsiblePersonForm,
      PersonForm,
      AuditState
    },
    mixins: [QueryDictMixin],
    computed: {
      ...mapState(login, ['supplierId', 'auditState', 'auditInfo']),
      isShowForm() {
        const flag = this.isEdit || this.auditState === 1
        return flag
      }
    },
    data() {
      return {
        stepList,
        activeStep: 0,
        loading: false,
        isEdit: false,
        dictKeys: ['system.whether'],
        srmDictKeys: [
          'bank_category',
          'shareholder_type',
          'certificate_type',
          'srm_supplier_info.qualification_category',
          'srm_supplier_info.economic_type',
          'srm_supplier_info.enterprise_type',
          'currency',
          'srm_supplier_info.enterprise_attribute',
          'srm_supplier_info.nature',
          'srm_supplier_info.source',
          'srm_supplier_info.audit_state'
          // ''
        ]
      }
    },
    watch: {
      auditState: {
        handler(val) {
          // 驳回后，修改
          if (this.auditState && this.auditState !== 1) {
            this.isEdit = false
          }
        },
        immediate: true,
        deep: true
      }
    },
    created() {
      Promise.all([
        this.initDictConfig(),
        // 所属国家
        this.initCountryOptions(),
        // 主供产物料分类型
        this.initServiceTypeOptions()
      ])
      this.isEdit = this.$route.query?.edit ? JSON.parse(this.$route.query.edit) : false
    },
    methods: {
      ...mapActions(login, ['getAuditDetail']),
      async initCountryOptions() {
        const { data } = await apiPostAreaTree({ areaLevel: 0, state: 1 })
        this.$set(this.dictOptions, 'country', data)
      },
      async initServiceTypeOptions() {
        const { data } = await apiPostGetServiceType({ state: 1 })
        this.$set(this.dictOptions, 'main_serve_type', data)
      },
      /**
       * 下一步操作
       * @param param  subType:submit:提交  next:下一步
       * @return {*|Promise}
       */
      handleSubmit: throttle(function (subType) {
        if (subType === 'submit') {
          this.handleCompleteInfo()
        } else if (subType === 'next') {
          const componentName = this.stepList[this.activeStep].component
          this.$refs[componentName].onSumit().then(() => {
            this.activeStep++
          })
        } else {
          this.activeStep--
        }
      }, 1000),
      // 提交审核
      handleCompleteInfo() {
        // 先保存在提交
        const componentName = this.stepList[this.activeStep].component
        this.$refs[componentName]
          .onSumit()
          .then(() => {
            apiGetSubmit(this.supplierId)
              .then(({ code }) => {
                if (code === EnumApiCode.Success) {
                  this.$message.success('已成功提交！')
                  this.getAuditDetail()
                  // this.getDetail()
                }
              })
              .catch(() => {})
          })
          .catch((error) => {
            this.$message.error(error)
          })
      },
      // 保存
      handleSubmitCom() {
        const componentName = this.stepList[this.activeStep].component
        this.$refs[componentName].onSumit(false).then(() => {
          this.$message.success('已成功保存！')
        })
      }
    }
  }
</script>
<style lang="scss">
  @import '../style/index.scss';
  .fade-form-enter-active {
    transition: all 0.6s ease-in 0.2s;
    opacity: 1;
    transform: translateX(0px);
  }

  .fade-form-leave-active {
    transition: all 0.2s ease-out;
    opacity: 0;
    transform: translateX(30px);
  }

  .fade-form-enter {
    opacity: 0;
    transform: translateX(-30px);
  }

  .fade-form-leave-to {
    opacity: 0;
    transform: translateX(0);
  }
  i.el-alert__icon.el-icon-error.is-big {
    position: relative;
    top: -10px;
  }
  .tips-text {
    font-size: 13px;
    line-height: 20px;
    margin-bottom: 5px;
  }
</style>
